<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/26
 * Time: 15:46
 */

namespace app\common\model;


use app\admin\controller\Play;
use think\Db;
use think\Model;
use wheat\Wheat;

class Room extends Model
{

    protected static $room_type = null;

    protected function initialize()
    {
        parent::initialize();
        self::$room_type = Play::$room_type;
    }


    public function profile()
    {

        return $this->hasOne('users', 'user_id', 'user_id')->field('nick_name,header_img');
    }

    public function getList($where = []){
        return $this
            ->where($where)
            ->order(['top'=>'desc','sort'=>'desc'])
//            ->field('room_name,top,cid,room_id,img,status,create_time,update_time,type')
            ->paginate(15,false,['query'=>request()->param()]);
    }


    public function getRows($map = [],$user_id = 0)
    {

        $rows = $this->alias('a')->where($map)
//            ->join([
//                [ 'users r','r.role_id = a.role_id','LEFT'],
//            ])
            ->field('a.room_id,a.cid,a.type,a.room_name,a.img,a.is_lock,a.password,a.user_id,a.room_type')
            ->order(['top'=>'desc','a.sort'=>'desc'])
            ->cache(10)
            //修改房间为非热度排序时   将分页数从100降到16
            ->paginate(16)->each(function ($item)use($user_id){

                $item['power'] = getPowerCode($user_id,$item['room_id']);
                $this->item($item);
                $item['user_id'] = hashid($item['user_id']);
            });
            $items = $rows->items();
            //去除根据热度排序
//            $last_names = array_column($items,'hot');
//            array_multisort($last_names,SORT_DESC,$items);

        return ['thisPage'=>$rows->currentPage(),'hasNext'=>$rows->hasMore(),'data'=>$items];
    }

    public function room($map = [],$user_id = 0,$room_id = 0)
    {
        $rows = $this->alias('a')->where($map)
//            ->join([
//                [ 'room_follow r','r.room_id = a.room_id','left'],
//            ])
            ->field('a.room_id,a.cid,a.type,a.room_name,a.img,a.is_lock,a.password,a.user_id,room_type')
            ->order(['top'=>'desc','room_id'=>'desc'])
            ->cache(10)
            ->select();
//            ->limit(2)
//            ->paginate()
//            ->each(function ($item)use ($user_id,$room_id){
//                if ($item['room_id'] == $room_id){
//                    $item['onRoom'] = 1;
//                }else{
//                    $item['onRoom'] = 0;
//                }
//                $item['power'] = getPowerCode($user_id,$item['room_id']);
//                $item = $this->item($item);
//                $item['user_id'] = hashid($item['user_id']);
//            });
//        return ['thisPage'=>$rows->currentPage(),'hasNext'=>$rows->hasMore(),'data'=>$rows->items(),'lastPage'=>$rows->lastPage()];

        if (!$rows) return [];
        foreach ($rows as $k => $item){
            if ($item['room_id'] == $room_id){
                $item['onRoom'] = 1;
            }else{
                $item['onRoom'] = 0;
            }
            $item['power'] = getPowerCode($user_id,$item['room_id']);
            $rows[$k] = $this->item($item);
            $rows[$k]['user_id'] = hashid($rows[$k]['user_id']);
        }
        return $rows;

    }


    public function rooms($map = [],$user_id = 0,$room_id = 0)
    {
        $rows = $this->alias('a')->where($map)
//            ->join([
//                [ 'room_follow r','r.room_id = a.room_id','left'],
//            ])
            ->field('a.room_id,a.cid,a.type,a.room_name,a.img,a.is_lock,a.password,a.user_id,a.room_type')
            ->order(['top'=>'desc','room_id'=>'desc'])
            ->cache(10)
//            ->limit(2)
            ->paginate()->each(function ($item)use ($user_id,$room_id){
                if ($item['room_id'] == $room_id){
                    $item['onRoom'] = 1;
                }else{
                    $item['onRoom'] = 0;
                }
                $item['power'] = getPowerCode($user_id,$item['room_id']);
                $item = $this->item($item);
                $item['user_id'] = hashid($item['user_id']);
            });
        return ['thisPage'=>$rows->currentPage(),'hasNext'=>$rows->hasMore(),'data'=>$rows->items(),'lastPage'=>$rows->lastPage()];

//        if (!$rows) return [];
//        foreach ($rows as $k => $item){
//            if ($item['room_id'] == $room_id){
//                $item['onRoom'] = 1;
//            }else{
//                $item['onRoom'] = 0;
//            }
//            $item['power'] = getPowerCode($user_id,$item['room_id']);
//            $rows[$k] = $this->item($item);
//            $rows[$k]['user_id'] = hashid($rows[$k]['user_id']);
//        }
//        return $rows;

    }
    
    public function item($item)
    {

        $item['hot'] = hotValue($item['room_id']);
//        if ($item['type'] == 4){
//            $item['type'] = Db::name('room_category')->where('cid',$item['cid'])->cache(60)->value('cate_name')??'';
//        }else{
//            $item['type'] = self::$room_type[$item['type']]['type_name'];
//        }
        $item['type'] = getRoomTypeName($item);
        $item['img']  = getThumb($item['img']);
        return $item;
    }



    public function getRows1($where = [])
    {
        $exp = new \think\db\Expression('field(a.play_status,1,2,0),a.update_time desc');
        $rows = $this->alias('a')->where($where)
            ->join([
                [ 'play_category b','b.cid = a.cid','LEFT'],
                [ 'role r','r.role_id = a.role_id','LEFT'],
            ])
            ->field('a.cid,b.cate_name,a.play_status,a.room_id,r.role_name,r.header_img,a.detail,a.img,a.room_name,a.VIP,a.official,a.fans')
            ->order($exp)
            ->cache(10)
            ->paginate();
//        var_dump( $rows);exit;
        $items = $rows->items();
        if (empty($items)) return false;
        foreach ($items as $k => $v){
            if ($v['play_status'] == 1){
                $guess['status'] = ['between','1,2'];
                $guess['room_id'] = $v['room_id'];
                $num = Db::name('guess')->where($guess)->count('guess_id');
                if ($num){
                    $items[$k]['remark'] = '竞猜';
                }else{
                    $items[$k]['remark'] = '直播中';
                }
            }elseif ($v['play_status'] == 0){
                $items[$k]['remark'] = '聊天开放中';
            }elseif ($v['play_status'] == 2){
                $items[$k]['remark'] = '直播预告';
            }
            $items[$k]['hot'] = hotValue($v['room_id']);
            $items[$k]['room_id'] = hashid($v['room_id']);
        }
        return ['thisPage'=>$rows->currentPage(),'hasNext'=>$rows->hasMore(),'data'=>$items,'lastPage'=>$rows->lastPage()];
    }
    
    
    
    
    public function detail($where = [])
    {
        return $this->alias('a')
            ->join('room_category b','b.cid = a.cid','LEFT')
            ->where($where)
            ->field('a.*,b.cate_name')->find();

    }

    public static function oneDetail($map = []){

        $data = self::where($map)
            ->field('img,room_name,is_lock,room_id,password')
            ->find();
        if ($data){
            $data['hot'] = hotValue($data['room_id']);
        }
        return $data;

    }


    public function joinRoom($room_id,$user_id = 0,$password = null)
    {
        $map['room_id'] = $room_id;
        $map['status']  = 1;

        $data = $this->where($map)->field('room_id,user_id,room_name,img,is_lock,password,notice,type,bg_id,is_free,cid')->cache(1)->find();
        if (!$data){
            api_return(0,'该房间已被封禁');
        }

        if ($data['type'] == 4){
            $data['cate_name'] = Db::name('room_category')->where('cid',$data['cid'])->value('cate_name')??'';
        }else{
            $data['cate_name'] = '';
        }


        $bg = RoomBackground::getBg($data['bg_id']);
        $data['bg_id']  = $bg['bg_id'];
        $data['bg_img'] = $bg['img'];
        
        $data['power'] = getPowerCode($user_id,$data['room_id']);

        //管理员免密码进入
        if ($data['is_lock']){
            if ($data['power'] == 4){
                if (empty($password) && !empty($data['password'])){
                    api_return(401,'请输入密码');
                }else{
                    if ($data['password'] != $password){
                        api_return(402,'密码错误');
                    }
                }
            }
        }

        $data['is_follow'] = \app\api\controller\Base::roomPower($data['room_id'],$user_id) == 0?0:1;


        $data['self'] = hashid($user_id);

        //查询用户是否被封禁
        $ban['user_id']  = $user_id;
        $ban['status']   = 1;
        $ban['end_time'] = ['>',time()];
        $ban['room_id']  = $room_id;
        $black = Db::name('room_blacklist')->where($ban)->cache(1)->value('end_time');
        if ($black){
            api_return(403,'您已被拉入黑名单',$black);
        }


        $wheat = Wheat::wheat($data['room_id'],$data['type']);
        $data['wheat'] = $wheat;

        unset($data['user_id']);

        return $data;
    }








}